package io.renren.common.pojo;

import io.renren.common.util.JsonUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.http.HttpStatus;

import java.io.Serializable;

/**
 * 返回数据
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年10月27日 下午9:59:27
 */
@Data
public class R<T> implements Serializable {
	private static final long serialVersionUID = 1L;

	private static final int SUCCESS_CODE = 0;
	private static final String SUCCESS_MSG = "success";

	@ApiModelProperty("状态码 0：成功  非0：失败")
	private Integer code;

	@ApiModelProperty("结果信息")
	private String msg;

	@ApiModelProperty("结果实体对象")
	private T entity;
	
	public R() {
		code = SUCCESS_CODE;
		msg = SUCCESS_MSG;
	}

	public R(String msg){
		this.msg = msg;
	}

	public R(T entity){
		this.entity = entity;
	}

	public R(int code,String msg){
		this.code = code;
		this.msg = msg;
	}
	
	public static R error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static R error(int code, String msg) {
		return new R(code,msg);
	}

	public static R ok(String msg) {
		R r = new R(msg);
		r.setCode(SUCCESS_CODE);
		return r;
	}
	
	public static <T> R<T> ok(T entity) {
		R<T> r = new R<>(entity);
		r.setCode(SUCCESS_CODE);
		r.setMsg(SUCCESS_MSG);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	public String toJson(){
		return JsonUtils.toJson(this);
	}
}
